// exam.js
Page({
  data: {
    currentIndex: 0,
    timeLeft: 0,
    examDuration: 0,
    showAnswer: false,
    questions: [],
    answerRecords: [],
    showResult: false,
    result: {
      correctCount: 0,
      timeUsed: 0,
      total: 0
    },
    paperId: ""
  },

  onLoad(options) {
    wx.showLoading({ title: '加载试题中...' });
    this.setData({ paperId: options.id });
    this.loadExamFromDB(options.id);
  },

  // 从数据库加载考试数据
  async loadExamFromDB(examId) {
    try {
      const res = await wx.cloud.database().collection('exams').where({id:examId}).get();
      this.processExamData(res.data[0]);
      this.loadProgress();
      this.startTimer();
    } catch (err) {
      wx.showToast({ 
        icon: 'error', 
        title: '加载失败',
        complete: () => {
          setTimeout(() => wx.navigateBack(), 2000);
        }
      });
      console.error('数据库查询失败:', err);
    }
    wx.hideLoading();
  },

  // 处理数据库返回的数据
  processExamData(examData) {
    const processedQuestions = examData.questions.map(q => ({
      ...q,
      correctAnswer: this.getCorrectAnswerText(q),
      isSingle: q.type === '单选题',
      isMulti: q.type === '多选题',
      isJudge: q.type === '判断题',
      options: q.options.map(opt => ({ 
        ...opt,
        selected: false 
      }))
    }));
    this.setData({
      questions: processedQuestions,
      timeLeft: Number(examData.duration) * 60 || 0,  // 确保数值类型
      examDuration: Number(examData.duration) * 60 || 0,
      'result.total': examData.questions.length
    });
  },

  // 获取正确答案文本
  getCorrectAnswerText(question) {
    const correctOptions = question.options.filter(opt => opt.correct);
    return correctOptions.map(opt => {
      const index = question.options.findIndex(o => o.id === opt.id);
      return `${String.fromCharCode(65 + index)}.${opt.text}`;
    }).join(' ');
  },

  // 加载进度
  loadProgress() {
    const saved = wx.getStorageSync(`examProgress_${this.data.paperId}`);
    if (saved) {
      this.setData({
        currentIndex: saved.currentIndex,
        timeLeft: saved.timeLeft,
        answerRecords: saved.answerRecords,
        questions: this.data.questions.map(q => {
          const savedRecord = saved.answerRecords.find(r => r.qid === q.id);
          return {
            ...q,
            options: q.options.map(opt => ({
              ...opt,
              selected: savedRecord?.selected?.includes(opt.id) || false
            }))
          };
        })
      });
    }
  },

  // 选择答案
  selectAnswer(e) {
    if (this.data.showAnswer || this.data.showResult) return;

    const { qid, optid } = e.currentTarget.dataset;
    const newQuestions = this.data.questions.map(question => {
      if (question.id === qid) {
        const options = question.options.map(option => {
          if (question.isSingle || question.isJudge) {
            return { ...option, selected: option.id === optid };
          }
          if (question.isMulti) {
            return option.id === optid 
              ? { ...option, selected: !option.selected }
              : option;
          }
          return option;
        });
        return { ...question, options };
      }
      return question;
    });

    this.setData({ questions: newQuestions }, () => {
      this.updateAnswerRecord(qid);
      this.showAnswerFeedback(qid);
    });
  },

  // 更新答题记录
  updateAnswerRecord(qid) {
    const question = this.data.questions.find(q => q.id === qid);
    const selected = question.options
      .filter(opt => opt.selected)
      .map(opt => opt.id);
    
    const isCorrect = this.checkAnswerCorrect(question, selected);
    const recordIndex = this.data.answerRecords.findIndex(r => r.qid === qid);

    if (recordIndex > -1) {
      this.data.answerRecords[recordIndex] = { qid, selected, isCorrect };
    } else {
      this.data.answerRecords.push({ qid, selected, isCorrect });
    }
  },

  // 验证答案正确性
  checkAnswerCorrect(question, selectedIds) {
    const correctIds = question.options
      .filter(opt => opt.correct)
      .map(opt => opt.id);

    if (question.isMulti) {
      return selectedIds.length === correctIds.length && 
        selectedIds.every(id => correctIds.includes(id));
    }
    return selectedIds[0] === correctIds[0];
  },

  // 显示答案反馈
  showAnswerFeedback(qid) {
    const currentQuestion = this.data.questions.find(q => q.id === qid);
    let showAnswer = false;
    let delay = 1500;
    let shouldProceed = false;

    if (currentQuestion.isMulti) {
      const selectedIds = currentQuestion.options
        .filter(opt => opt.selected)
        .map(opt => opt.id);
      const correctIds = currentQuestion.options
        .filter(opt => opt.correct)
        .map(opt => opt.id);

      const hasWrong = selectedIds.some(id => !correctIds.includes(id));
      const isComplete = selectedIds.length >= correctIds.length;

      if (hasWrong || (isComplete && !hasWrong)) {
        showAnswer = true;
        shouldProceed = true;
        delay = hasWrong ? 1000 : 2000;
      }
    } else {
      showAnswer = true;
      shouldProceed = true;
    }

    this.setData({ showAnswer }, () => {
      if (shouldProceed) {
        setTimeout(() => {
          if (this.data.currentIndex < this.data.questions.length - 1) {
            this.setData({ 
              currentIndex: this.data.currentIndex + 1,
              showAnswer: false 
            });
          } else {
            this.submitExam();
          }
          this.saveProgress();
        }, delay);
      }
    });
  },

  // 启动计时器
  startTimer() {
    this.timer = setInterval(() => {
      if (this.data.timeLeft > 0) {
        this.setData({ timeLeft: this.data.timeLeft - 1 });
        this.saveProgress();
      } else {
        this.submitExam();
      }
    }, 1000);
  },

  // 提交考试
  submitExam() {
    clearInterval(this.timer);
    wx.removeStorageSync(`examProgress_${this.data.paperId}`);
    
    const correctCount = this.data.answerRecords
      .filter(r => r.isCorrect).length;
    
    this.setData({
      showResult: true,
      'result.correctCount': correctCount,
      'result.timeUsed': this.data.examDuration - this.data.timeLeft
    });
  },

  // 保存进度
  saveProgress() {
    wx.setStorageSync(`examProgress_${this.data.paperId}`, {
      currentIndex: this.data.currentIndex,
      timeLeft: this.data.timeLeft,
      answerRecords: this.data.answerRecords
    });
  },

  // 处理滑动切换
  swiperChange(e) {
    if (this.data.showAnswer) {
      this.setData({ currentIndex: this.data.currentIndex });
      return;
    }
    this.setData({ currentIndex: e.detail.current });
  },

  // 时间格式化
  formatTime(seconds) {
    const mins = Math.floor(seconds / 60).toString().padStart(2, '0');
    const secs = (seconds % 60).toString().padStart(2, '0');
    return `${mins}:${secs}`;
  },

  formatResultTime(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}分${secs.toString().padStart(2, '0')}秒`;
  },

  // 重新考试
  restartExam() {
    this.setData({
      currentIndex: 0,
      timeLeft: this.data.examDuration,
      showAnswer: false,
      answerRecords: [],
      showResult: false,
      result: { correctCount: 0, timeUsed: 0, total: this.data.result.total }
    });
    wx.removeStorageSync(`examProgress_${this.data.paperId}`);
    this.startTimer();
  },

  // 退出考试
  exitExam() {
    wx.navigateBack();
  },

  // 页面卸载处理
  onUnload() {
    clearInterval(this.timer);
    this.saveProgress();
  }
});